<template>
  <div class="smart-qa-container">
    <!-- 左侧历史记录 -->
    <div class="history-sidebar">
      <div class="history-header">
        <h3>历史对话</h3>
        <button class="new-chat-btn" @click="startNewChat">
          <i class="plus-icon"></i>
          新对话
        </button>
      </div>
      <div class="history-list">
        <div 
          v-for="chat in chatHistory" 
          :key="chat.id"
          class="history-item"
          :class="{ active: currentChatId === chat.id }"
          @click="selectChat(chat.id)"
        >
          <div class="chat-title">{{ chat.title }}</div>
          <div class="chat-time">{{ formatTime(chat.lastTime) }}</div>
        </div>
        <div v-if="chatHistory.length === 0" class="empty-history">
          暂无历史对话
        </div>
      </div>
    </div>

    <!-- 右侧对话区域 -->
    <div class="chat-area">
      <div class="chat-header">
        <h2>智能问答助手</h2>
        <p class="chat-subtitle">我是您的职场智能助手，可以为您解答求职、面试、职业规划等问题</p>
      </div>

      <div class="chat-messages" ref="messagesContainer">
        <div v-if="currentMessages.length === 0" class="welcome-message">
          <div class="welcome-content">
            <div class="welcome-icon">🤖</div>
            <h3>欢迎使用智能问答</h3>
            <p>您可以问我关于以下内容的问题：</p>
            <div class="suggestion-tags">
              <span class="tag" @click="askSuggestion('如何写一份优秀的简历？')">简历撰写</span>
              <span class="tag" @click="askSuggestion('面试时需要注意什么？')">面试技巧</span>
              <span class="tag" @click="askSuggestion('如何进行职业规划？')">职业规划</span>
              <span class="tag" @click="askSuggestion('如何提升职场竞争力？')">能力提升</span>
            </div>
          </div>
        </div>

        <div 
          v-for="message in currentMessages" 
          :key="message.id"
          class="message-item"
          :class="{ 'user-message': message.type === 'user', 'ai-message': message.type === 'ai' }"
        >
          <div class="message-avatar">
            <div v-if="message.type === 'user'" class="user-avatar">👤</div>
            <div v-else class="ai-avatar">🤖</div>
          </div>
          <div class="message-content">
            <div class="message-text" :class="{ 'streaming': message.isStreaming }">
              <span v-if="message.isStreaming" class="streaming-content" v-html="message.content"></span>
              <span v-else v-html="message.content"></span>
              <span v-if="message.isStreaming" class="streaming-cursor">|</span>
            </div>
            <div class="message-actions" v-if="message.type === 'ai' && (message.content.includes('⏱️') || message.content.includes('🌐') || message.content.includes('❌'))">
              <button class="retry-btn" @click="retryLastMessage">
                🔄 重试
              </button>
            </div>
            <div class="message-time">{{ formatTime(message.time) }}</div>
          </div>
        </div>

        <div v-if="isTyping" class="message-item ai-message typing">
          <div class="message-avatar">
            <div class="ai-avatar">🤖</div>
          </div>
          <div class="message-content">
            <div class="typing-indicator">
              <span></span>
              <span></span>
              <span></span>
            </div>
          </div>
        </div>
      </div>

      <div class="chat-input-area">
        <div class="input-container">
          <textarea
            v-model="inputMessage"
            ref="messageInput"
            placeholder="请输入您的问题..."
            class="message-input"
            :disabled="isStreaming"
            rows="1"
            @keydown.enter.prevent="handleEnter"
            @input="adjustTextareaHeight"
          ></textarea>
          <button 
            v-if="!isStreaming"
            class="send-btn" 
            :disabled="!inputMessage.trim() || isTyping"
            @click="sendMessage"
          >
            <i class="send-icon"></i>
          </button>
          <button 
            v-else
            class="cancel-btn" 
            @click="cancelStreaming"
          >
            <i class="cancel-icon"></i>
          </button>
        </div>
        <div class="input-tips">
          按 Enter 发送，Shift + Enter 换行
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, onUnmounted } from 'vue'
import request from '@/utils/request.js'

// 响应式数据
const inputMessage = ref('')
const isTyping = ref(false)
const isStreaming = ref(false)
const currentChatId = ref(null)
const messagesContainer = ref(null)
const messageInput = ref(null)
const currentEventSource = ref(null)

// 聊天历史
const chatHistory = reactive([
  {
    id: 1,
    title: '简历优化建议',
    lastTime: new Date(Date.now() - 1000 * 60 * 30), // 30分钟前
    messages: [
      {
        id: 1,
        type: 'user',
        content: '如何写一份优秀的简历？',
        time: new Date(Date.now() - 1000 * 60 * 30)
      },
      {
        id: 2,
        type: 'ai',
        content: '写一份优秀简历的关键要点包括：\n\n1. **突出核心信息**：姓名、联系方式、求职意向要清晰明确\n2. **量化工作成果**：用具体数字展示你的业绩和贡献\n3. **技能匹配**：针对目标岗位突出相关技能和经验\n4. **简洁明了**：控制在1-2页，避免冗余信息\n5. **专业格式**：使用清晰的排版和专业的字体\n\n需要我为您详细解释某个方面吗？',
        time: new Date(Date.now() - 1000 * 60 * 29)
      }
    ]
  },
  {
    id: 2,
    title: '面试准备指南',
    lastTime: new Date(Date.now() - 1000 * 60 * 60 * 2), // 2小时前
    messages: [
      {
        id: 1,
        type: 'user',
        content: '面试时需要注意什么？',
        time: new Date(Date.now() - 1000 * 60 * 60 * 2)
      },
      {
        id: 2,
        type: 'ai',
        content: '面试成功的关键要素：\n\n**面试前准备**\n• 深入了解公司背景和职位要求\n• 准备常见问题的回答\n• 整理相关作品和证书\n\n**面试中表现**\n• 保持自信和专业的形象\n• 主动沟通，展示你的热情\n• 准备有质量的问题询问面试官\n\n**注意事项**\n• 准时到达，最好提前10-15分钟\n• 关闭手机或调至静音\n• 保持良好的身体语言和眼神交流',
        time: new Date(Date.now() - 1000 * 60 * 60 * 2 + 1000 * 30)
      }
    ]
  }
])

// 当前对话消息
const currentMessages = ref([])

// 方法
const formatTime = (date) => {
  const now = new Date()
  const diff = now - date
  
  if (diff < 1000 * 60) return '刚刚'
  if (diff < 1000 * 60 * 60) return `${Math.floor(diff / (1000 * 60))}分钟前`
  if (diff < 1000 * 60 * 60 * 24) return `${Math.floor(diff / (1000 * 60 * 60))}小时前`
  return date.toLocaleDateString()
}

const selectChat = (chatId) => {
  currentChatId.value = chatId
  const chat = chatHistory.find(c => c.id === chatId)
  if (chat) {
    currentMessages.value = [...chat.messages]
    nextTick(() => {
      scrollToBottom()
    })
  }
}

const startNewChat = () => {
  currentChatId.value = null
  currentMessages.value = []
  inputMessage.value = ''
}

const askSuggestion = (question) => {
  inputMessage.value = question
  sendMessage()
}

const handleEnter = (event) => {
  if (event.shiftKey) {
    return // 允许换行
  }
  sendMessage()
}

const adjustTextareaHeight = () => {
  const textarea = messageInput.value
  if (textarea) {
    textarea.style.height = 'auto'
    textarea.style.height = Math.min(textarea.scrollHeight, 120) + 'px'
  }
}

const sendMessage = async () => {
  if (!inputMessage.value.trim() || isTyping.value || isStreaming.value) return

  const userMessage = {
    id: Date.now(),
    type: 'user',
    content: inputMessage.value.trim(),
    time: new Date()
  }

  const questionText = inputMessage.value.trim()

  // 如果是新对话，创建新的聊天记录
  if (!currentChatId.value) {
    const newChat = {
      id: Date.now(),
      title: userMessage.content.slice(0, 20) + (userMessage.content.length > 20 ? '...' : ''),
      lastTime: new Date(),
      messages: []
    }
    chatHistory.unshift(newChat)
    currentChatId.value = newChat.id
    currentMessages.value = []
  }

  currentMessages.value.push(userMessage)
  inputMessage.value = ''
  
  nextTick(() => {
    adjustTextareaHeight()
    scrollToBottom()
  })

  // 显示输入状态
  isTyping.value = true
  isStreaming.value = true

  try {
    // 创建AI消息占位符
    const aiMessage = {
      id: Date.now() + 1,
      type: 'ai',
      content: '',
      time: new Date(),
      isStreaming: true
    }
    currentMessages.value.push(aiMessage)
    
    // 调用流式接口
    console.log('发送流式请求到后台接口:', {
      url: '/qa/qa-sse-test/',
      question: questionText,
      baseURL: 'http://localhost:8000/'
    })
    
    // 使用fetch API进行POST SSE连接
    const abortController = new AbortController()
    currentEventSource.value = abortController
    
    const response = await fetch('http://localhost:8000/qa/qa-sse-test/', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Cache-Control': 'no-cache'
      },
      body: JSON.stringify({
        question: questionText
      }),
      signal: abortController.signal
    })
    
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`)
    }
    
    console.log('SSE连接已建立')
    isTyping.value = false // 连接建立后隐藏"正在输入"状态
    
    const reader = response.body.getReader()
    const decoder = new TextDecoder()
    
    // 存储接收到的原始数据
    let accumulatedContent = ''
    let displayQueue = [] // 显示队列
    let isProcessingQueue = false // 是否正在处理队列
    
    // 处理显示队列的函数 - 简化版本
    const processDisplayQueue = async () => {
      if (isProcessingQueue) return
      isProcessingQueue = true
      
      console.log('开始处理显示队列，队列长度:', displayQueue.length)
      
      while (displayQueue.length > 0) {
        const contentChunk = displayQueue.shift()
        console.log('正在显示内容块:', contentChunk)
        
        // 直接将整个内容块添加到显示内容
        aiMessage.content += contentChunk
        
        console.log('更新后的内容长度:', aiMessage.content.length)
        console.log('更新后的内容末尾:', aiMessage.content.slice(-20))
        
        // 强制更新整个消息数组
        const messageIndex = currentMessages.value.findIndex(m => m.id === aiMessage.id)
        if (messageIndex !== -1) {
          currentMessages.value.splice(messageIndex, 1, { 
            ...aiMessage,
            content: aiMessage.content
          })
        }
        
        // 等待DOM更新完成
        await nextTick()
        
        // 滚动到底部
        scrollToBottom()
        
        // 内容块之间的暂停时间
        await new Promise(resolve => setTimeout(resolve, 200))
      }
      
      console.log('显示队列处理完成')
      isProcessingQueue = false
    }
    
    // 处理流式响应
    const processStream = async () => {
      try {
        while (true) {
          const { done, value } = await reader.read()
          
          if (done) {
            console.log('流式输出完成')
            aiMessage.isStreaming = false
            isTyping.value = false
            isStreaming.value = false
            currentEventSource.value = null
            
            // 更新聊天历史
            const currentChat = chatHistory.find(c => c.id === currentChatId.value)
            if (currentChat) {
              currentChat.messages = [...currentMessages.value]
              currentChat.lastTime = new Date()
            }
            break
          }
          
          const chunk = decoder.decode(value, { stream: true })
          console.log('接收到流式数据块:', chunk)
          const lines = chunk.split('\n')
          
          for (const line of lines) {
            const trimmedLine = line.trim()
            if (!trimmedLine) continue
            
            if (trimmedLine.startsWith('data: ')) {
              const data = trimmedLine.slice(6) // 移除 'data: ' 前缀
              console.log('解析SSE行数据:', data)
              
              if (data.trim() === '') continue
              if (data.trim() === '[DONE]') {
                console.log('流式输出完成')
                aiMessage.isStreaming = false
                isTyping.value = false
                isStreaming.value = false
                currentEventSource.value = null
                
                // 更新聊天历史
                const currentChat = chatHistory.find(c => c.id === currentChatId.value)
                if (currentChat) {
                  currentChat.messages = [...currentMessages.value]
                  currentChat.lastTime = new Date()
                }
                return
              }
              
              try {
                const parsedData = JSON.parse(data)
                console.log('收到流式数据:', parsedData)
                console.log('当前时间:', new Date().toLocaleTimeString())
                
                if (parsedData.content) {
                  // 累积内容
                  accumulatedContent += parsedData.content
                  console.log('累积内容更新:', accumulatedContent)
                  console.log('新增内容:', parsedData.content)
                  
                  // 添加到显示队列
                  displayQueue.push(parsedData.content)
                  
                  // 如果没有在处理队列，开始处理
                  if (!isProcessingQueue) {
                    processDisplayQueue()
                  }
                } else if (parsedData.error) {
                  // 服务器返回错误
                  accumulatedContent += `\n\n[错误] ${parsedData.error}`
                  aiMessage.content = accumulatedContent
                  aiMessage.isStreaming = false
                  isTyping.value = false
                  isStreaming.value = false
                  currentEventSource.value = null
                  
                  // 更新聊天历史
                  const currentChat = chatHistory.find(c => c.id === currentChatId.value)
                  if (currentChat) {
                    currentChat.messages = [...currentMessages.value]
                    currentChat.lastTime = new Date()
                  }
                  return
                }
                
              } catch (parseError) {
                console.error('解析SSE数据失败:', parseError, '原始数据:', data)
                // 如果不是JSON格式，可能是纯文本流式数据
                if (data.trim()) {
                  accumulatedContent += data
                  aiMessage.content = accumulatedContent
                  
                  // 立即滚动到底部
                  nextTick(() => {
                    scrollToBottom()
                  })
                }
              }
            }
          }
        }
      } catch (streamError) {
        if (streamError.name === 'AbortError') {
          console.log('流式请求被用户取消')
          return
        }
        
        console.error('处理流式响应时出错:', streamError)
        aiMessage.content = aiMessage.content || '连接中断，请重试。'
        aiMessage.isStreaming = false
        isTyping.value = false
        isStreaming.value = false
        currentEventSource.value = null
        
        nextTick(() => {
          scrollToBottom()
        })
      }
    }
    
    // 开始处理流式响应
    processStream()
    
    // 设置超时处理
    const timeout = setTimeout(() => {
      if (currentEventSource.value) {
        abortController.abort()
        aiMessage.content = aiMessage.content || '⏱️ 请求超时了，AI正在思考一个复杂的问题。请稍后重试，或者尝试提出更简洁的问题。'
        aiMessage.isStreaming = false
        isTyping.value = false
        isStreaming.value = false
        currentEventSource.value = null
        
        nextTick(() => {
          scrollToBottom()
        })
      }
    }, 60000) // 60秒超时
    
    // 当连接关闭时清除超时
    abortController.signal.addEventListener('abort', () => {
      clearTimeout(timeout)
    })
    
    // 更新聊天历史
    const currentChat = chatHistory.find(c => c.id === currentChatId.value)
    if (currentChat) {
      currentChat.messages = [...currentMessages.value]
      currentChat.lastTime = new Date()
    }
    
  } catch (error) {
    console.error('调用智能问答接口失败:', error)
    
    let errorContent = ''
    
    if (error.code === 'ECONNABORTED') {
      // 超时错误
      errorContent = '⏱️ 请求超时了，AI正在思考一个复杂的问题。请稍后重试，或者尝试提出更简洁的问题。'
    } else if (error.code === 'NETWORK_ERROR' || error.message.includes('Network Error')) {
      // 网络错误
      errorContent = '🌐 网络连接出现问题，请检查您的网络连接后重试。'
    } else if (error.response) {
      // 服务器响应错误
      const status = error.response.status
      if (status === 500) {
        errorContent = '🔧 服务器内部错误，我们的技术团队正在处理。请稍后重试。'
      } else if (status === 404) {
        errorContent = '❓ 接口地址不存在，请联系技术支持。'
      } else {
        errorContent = `⚠️ 服务暂时不可用 (错误码: ${status})，请稍后重试。`
      }
    } else {
      // 其他错误
      errorContent = '❌ 出现了未知错误，请稍后重试。如果问题持续存在，请联系技术支持。'
    }
    
    // 显示错误消息
    const errorMessage = {
      id: Date.now() + 1,
      type: 'ai',
      content: errorContent,
      time: new Date()
    }
    
    currentMessages.value.push(errorMessage)
    
    // 更新聊天历史
    const currentChat = chatHistory.find(c => c.id === currentChatId.value)
    if (currentChat) {
      currentChat.messages = [...currentMessages.value]
      currentChat.lastTime = new Date()
    }
  } finally {
    // 对于流式输出，输入状态会在流完成后隐藏
    // 这里只处理非流式的情况
    if (isTyping.value) {
      isTyping.value = false
    }
    
    nextTick(() => {
      scrollToBottom()
    })
  }
}

const cancelStreaming = () => {
  if (currentEventSource.value) {
    // AbortController取消请求
    if (typeof currentEventSource.value.abort === 'function') {
      currentEventSource.value.abort()
    }
    currentEventSource.value = null
  }
  
  isTyping.value = false
  isStreaming.value = false
  
  // 找到最后一条正在流式输出的消息并标记为已取消
  const messages = currentMessages.value
  for (let i = messages.length - 1; i >= 0; i--) {
    if (messages[i].isStreaming) {
      messages[i].isStreaming = false
      messages[i].content += '\n\n[用户取消了回答]'
      break
    }
  }
  
  console.log('用户取消了流式输出')
}

const retryLastMessage = () => {
  // 找到最后一个用户消息
  const messages = currentMessages.value
  for (let i = messages.length - 1; i >= 0; i--) {
    if (messages[i].type === 'user') {
      inputMessage.value = messages[i].content
      sendMessage()
      break
    }
  }
}

const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

// 打字机效果函数（现在主要用于非流式场景）
const typeWriterEffect = (messageObj, fullText) => {
  // 清除之前的定时器，避免重复执行
  if (messageObj._typewriterTimer) {
    messageObj._typewriterTimer.forEach(timer => clearTimeout(timer));
    messageObj._typewriterTimer = [];
  }
  
  let i = messageObj.content.length;
  const targetLength = fullText.length;
  
  if (i < targetLength) {
    const timer = setTimeout(() => {
      // 每次增加1个字符
      messageObj.content = fullText.substring(0, i + 1);
      
      // 滚动到底部
      nextTick(() => {
        scrollToBottom();
      });
      
      // 继续下一个字符
      typeWriterEffect(messageObj, fullText);
    }, 20); // 20ms间隔，控制打字速度
    
    // 将定时器ID存储在消息对象上，以便可以取消
    if (!messageObj._typewriterTimer) {
      messageObj._typewriterTimer = [];
    }
    messageObj._typewriterTimer.push(timer);
  }
};

// 流式内容的打字机效果函数
const typeWriterEffectForStreaming = (messageObj, newContent) => {
  if (!newContent) return;
  
  const startContent = messageObj.content;
  const targetContent = startContent + newContent;
  let currentIndex = startContent.length;
  
  const typeNextChar = () => {
    if (currentIndex < targetContent.length) {
      messageObj.content = targetContent.substring(0, currentIndex + 1);
      currentIndex++;
      
      // 滚动到底部
      nextTick(() => {
        scrollToBottom();
      });
      
      // 继续下一个字符
      setTimeout(typeNextChar, 30); // 30ms间隔
    }
  };
  
  typeNextChar();
};

// 组件挂载时的初始化
onMounted(() => {
  // 默认选择第一个对话
  if (chatHistory.length > 0) {
    selectChat(chatHistory[0].id)
  }
})

// 在组件卸载时清理定时器
onUnmounted(() => {
  // 清理所有打字机效果定时器
  currentMessages.value.forEach(message => {
    if (message._typewriterTimer) {
      message._typewriterTimer.forEach(timer => clearTimeout(timer));
      message._typewriterTimer = null;
    }
  });
});

</script>

<style scoped>
.smart-qa-container {
  display: flex;
  height: calc(100vh - 49px);
  margin-top: 49px;
  background: #f5f7fa;
}

/* 左侧历史记录 */
.history-sidebar {
  width: 280px;
  background: #fff;
  border-right: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;
}

.history-header {
  padding: 20px;
  border-bottom: 1px solid #e4e7ed;
}

.history-header h3 {
  margin: 0 0 15px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.new-chat-btn {
  width: 100%;
  padding: 10px;
  background: #00BEBD;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  font-size: 14px;
  transition: background-color 0.3s;
}

.new-chat-btn:hover {
  background: #009a9a;
}

.plus-icon::before {
  content: '+';
  font-size: 16px;
  font-weight: bold;
}

.history-list {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.history-item {
  padding: 12px;
  margin-bottom: 8px;
  border-radius: 8px;
  cursor: pointer;
  transition: background-color 0.2s;
  border: 1px solid transparent;
}

.history-item:hover {
  background: #f5f7fa;
}

.history-item.active {
  background: #e6f9f9;
  border-color: #00BEBD;
}

.chat-title {
  font-size: 14px;
  color: #303133;
  margin-bottom: 4px;
  font-weight: 500;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.chat-time {
  font-size: 12px;
  color: #909399;
}

.empty-history {
  text-align: center;
  color: #909399;
  font-size: 14px;
  padding: 40px 20px;
}

/* 右侧对话区域 */
.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #fff;
}

.chat-header {
  padding: 20px 30px;
  border-bottom: 1px solid #e4e7ed;
  background: #fff;
}

.chat-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 20px;
  font-weight: 600;
}

.chat-subtitle {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px 30px;
  background: #fafbfc;
}

.welcome-message {
  text-align: center;
  padding: 60px 20px;
}

.welcome-content {
  max-width: 500px;
  margin: 0 auto;
}

.welcome-icon {
  font-size: 48px;
  margin-bottom: 20px;
}

.welcome-content h3 {
  color: #303133;
  font-size: 24px;
  margin-bottom: 10px;
}

.welcome-content p {
  color: #606266;
  font-size: 16px;
  margin-bottom: 30px;
}

.suggestion-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  justify-content: center;
}

.tag {
  padding: 8px 16px;
  background: #e6f9f9;
  color: #00BEBD;
  border-radius: 20px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
  border: 1px solid #00BEBD;
}

.tag:hover {
  background: #00BEBD;
  color: white;
}

.message-item {
  display: flex;
  margin-bottom: 20px;
  align-items: flex-start;
}

.user-message {
  flex-direction: row-reverse;
}

.message-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  margin: 0 15px;
  flex-shrink: 0;
}

.user-avatar {
  background: #00BEBD;
  color: white;
}

.ai-avatar {
  background: #f0f2f5;
  color: #606266;
}

.message-content {
  max-width: 70%;
  min-width: 100px;
}

.user-message .message-content {
  text-align: right;
}

.message-text {
  background: #fff;
  padding: 12px 16px;
  border-radius: 12px;
  font-size: 14px;
  line-height: 1.5;
  color: #303133;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  white-space: pre-wrap;
}

.user-message .message-text {
  background: #00BEBD;
  color: white;
}

.message-text.streaming {
  position: relative;
}

.streaming-content {
  white-space: pre-wrap;
}

.streaming-cursor {
  display: inline-block;
  color: #00BEBD;
  font-weight: bold;
  animation: blink 1s infinite;
}

@keyframes blink {
  0%, 50% { opacity: 1; }
  51%, 100% { opacity: 0; }
}

.message-actions {
  margin: 8px 0;
}

.retry-btn {
  background: #f0f2f5;
  border: 1px solid #dcdfe6;
  color: #606266;
  padding: 4px 12px;
  border-radius: 16px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.3s;
}

.retry-btn:hover {
  background: #00BEBD;
  color: white;
  border-color: #00BEBD;
}

.message-time {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.user-message .message-time {
  text-align: right;
}

.typing {
  opacity: 0.8;
}

.typing-indicator {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 12px 16px;
  background: #f0f2f5;
  border-radius: 12px;
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  background: #909399;
  border-radius: 50%;
  animation: typing 1.4s infinite ease-in-out;
}

.typing-indicator span:nth-child(1) {
  animation-delay: -0.32s;
}

.typing-indicator span:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes typing {
  0%, 80%, 100% {
    opacity: 0.3;
    transform: scale(0.8);
  }
  40% {
    opacity: 1;
    transform: scale(1);
  }
}

/* 输入区域 */
.chat-input-area {
  padding: 20px 30px;
  border-top: 1px solid #e4e7ed;
  background: #fff;
}

.input-container {
  display: flex;
  align-items: flex-end;
  gap: 15px;
  margin-bottom: 8px;
}

.message-input {
  flex: 1;
  min-height: 44px;
  max-height: 120px;
  padding: 12px 16px;
  border: 1px solid #dcdfe6;
  border-radius: 22px;
  font-size: 14px;
  line-height: 1.4;
  resize: none;
  outline: none;
  font-family: inherit;
  transition: border-color 0.3s;
}

.message-input:focus {
  border-color: #00BEBD;
}

.message-input:disabled {
  background-color: #f5f7fa;
  color: #c0c4cc;
  cursor: not-allowed;
}

.send-btn {
  width: 44px;
  height: 44px;
  background: #00BEBD;
  color: white;
  border: none;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.3s;
  flex-shrink: 0;
}

.send-btn:hover:not(:disabled) {
  background: #009a9a;
}

.send-btn:disabled {
  background: #c0c4cc;
  cursor: not-allowed;
}

.cancel-btn {
  width: 44px;
  height: 44px;
  background: #f56c6c;
  color: white;
  border: none;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.3s;
  flex-shrink: 0;
}

.cancel-btn:hover {
  background: #e54545;
}

.send-icon::before {
  content: '➤';
  font-size: 16px;
}

.cancel-icon::before {
  content: '✕';
  font-size: 16px;
  font-weight: bold;
}

.input-tips {
  font-size: 12px;
  color: #909399;
  text-align: center;
}

/* 滚动条样式 */
.history-list::-webkit-scrollbar,
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.history-list::-webkit-scrollbar-track,
.chat-messages::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.history-list::-webkit-scrollbar-thumb,
.chat-messages::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.history-list::-webkit-scrollbar-thumb:hover,
.chat-messages::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .smart-qa-container {
    flex-direction: column;
  }
  
  .history-sidebar {
    width: 100%;
    height: 200px;
  }
  
  .message-content {
    max-width: 85%;
  }
  
  .chat-messages {
    padding: 15px 20px;
  }
  
  .chat-input-area {
    padding: 15px 20px;
  }
}
</style>
